<template>
    <div class="app-container">
        <el-form
            :inline="true"
            size="mini"
            class="update-search-form"
            ref="updateSearchForm"
            :model="updateSearchForm"
        >
            <el-form-item label="升级时间">
                <el-date-picker
                    style="width: 220px"
                    :append-to-body="false"
                    :popper-append-to-body="false"
                    v-model="rangeData"
                    type="daterange"
                    align="right"
                    unlink-panels
                    value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :picker-options="pickerOptions"
                >
                </el-date-picker>
            </el-form-item>

            <el-form-item label="类型">
                <el-select
                    v-model="updateSearchForm.type"
                    placeholder="请选择类型"
                    clearable
                >
                    <el-option
                        v-for="item in enumsJson.EQUIP_UPGRADE_TASK_TYPE.filter(
                            (item) => item.code != 'SCHEDULE'
                        )"
                        :key="item.code"
                        :label="item.label"
                        :value="item.code"
                    >
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-search"
                    @click="doSearch"
                    >搜索</el-button
                >
                <el-button
                    type="default"
                    size="mini"
                    icon="el-icon-refresh"
                    @click="resetSearch"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>
        <div class="searchs-content">
            <el-button
                v-permission="['version:manualupgrade:add']"
                type="primary"
                size="mini"
                plain
                icon="el-icon-plus"
                @click="addDialog"
                >新增</el-button
            >
        </div>
        <Table
            :tableHeader="updateTableHeader"
            :tableData="tableData"
            :tableLoading="listLoading"
        >
            <template slot="executes" slot-scope="scope">
                <div>
                    <el-tag v-if="scope.row.status === 0" type="info"
                        >未开始</el-tag
                    >
                    <el-tag v-else-if="scope.row.status === 1" type="primary"
                        >执行中</el-tag
                    >
                    <el-tag v-else-if="scope.row.status === 2" type="success"
                        >完成</el-tag
                    >
                    <el-tag v-else type="danger">{{ scope.row.status }}</el-tag>
                </div>
            </template>
            <template slot="action" slot-scope="scope">
                <el-button
                    type="warning"
                    size="mini"
                    @click="detailDialog(scope.row)"
                    >详情</el-button
                >
                <el-button
                    type="primary"
                    size="mini"
                    v-permission="['version:manualupgrade:edit']"
                    v-if="
                        scope.row.status == 0 &&
                        scope.row.type == 'BATCH_SCHEDULE'
                    "
                    @click="editDialog(scope.row)"
                    >编辑</el-button
                >
                <!-- 定时批次 未执行时可删除 -->
                <el-button
                    type="danger"
                    size="mini"
                    v-if="
                        scope.row.status == 0 &&
                        scope.row.type == 'BATCH_SCHEDULE'
                    "
                    @click="isDelete(scope.row)"
                    v-permission="['version:manualupgrade:delete']"
                    >删除</el-button
                >
            </template>
        </Table>
        <pagination
            v-if="total > 0"
            :total="total"
            :page.sync="updateSearchForm.pageNum"
            :limit.sync="updateSearchForm.pageSize"
            @pagination="fetchData"
        />

        <!-- 弹框 -->
        <Dialog
            class="handleDialog"
            :visible="visible"
            width="80%"
            :isFullscreen="isFullscreen"
            :isFooter="false"
            title="新增"
            @cancelDialog="cancelDialog"
        >
            <i
                class="el-icon-full-screen"
                @click="onFullscreen('isFullscreen')"
            ></i>
            <el-form
                class="filters searchForm"
                ref="searchForm"
                :model="searchForm"
                label-width="78px"
                size="mini"
            >
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="设备编码" style="width: 100%">
                            <el-input
                                type="textarea"
                                :rows="3"
                                :placeholder="'请输入柜号，多个编码之间请回车换行，禁止输入特殊字符！输入示例：\nCC08DPC0202204250001\nCC08DPC0202205070001\n0000092011500063'"
                                v-model="searchForm.codes"
                                @change.native="keyUp($event)"
                                @input.native="keyInput($event)"
                            >
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="19" class="filters">
                        <el-form-item label="厂商" v-if="platformType == 'P'">
                            <el-select
                                v-model="searchForm.organizationId"
                                placeholder="请选择厂商"
                                clearable
                                @change="organizeChange"
                            >
                                <el-option
                                    v-for="item in factuerOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="运营商">
                            <el-select
                                clearable
                                :disabled="!searchForm.organizationId"
                                v-model="searchForm.operatorId"
                                placeholder="请先选择厂商"
                            >
                                <el-option
                                    v-for="item in operatorOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="设备类型">
                            <el-select
                                v-model="searchForm.equipTypeCode"
                                @change="equipTypeChange"
                                placeholder="请选择设备类型"
                            >
                                <el-option
                                    v-for="item in equipTypeOption"
                                    :key="item.code"
                                    :label="item.name"
                                    :value="item.code"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="部件">
                            <el-select
                                v-model="searchForm.partType"
                                :disabled="!searchForm.equipTypeCode"
                                placeholder="请选择部件"
                            >
                                <el-option
                                    v-for="item in componentList"
                                    :key="item.code"
                                    :label="item.name"
                                    :value="item.code"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="版本">
                            <el-input
                                v-model="searchForm.version"
                                :disabled="!searchForm.partType"
                                placeholder="请输入版本"
                            />
                        </el-form-item>
                        <el-form-item label="业务状态">
                            <el-select
                                v-model="searchForm.statuses"
                                multiple
                                placeholder="请选择业务状态"
                            >
                                <el-option
                                    v-for="item in businessStatus"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="联网状态">
                            <el-select
                                v-model="searchForm.isOnline"
                                placeholder="请选择联网状态"
                            >
                                <el-option
                                    v-for="item in isOnlineStatus"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="标签">
                            <el-select
                                v-model="searchForm.tagIds"
                                multiple
                                collapse-tags
                                placeholder="请选择标签"
                                clearable
                            >
                                <el-option
                                    v-for="item in tagsOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="地区" class="area-select">
                            <el-cascader
                                :options="areaSelectData"
                                :props="areaSelectDataProps"
                                ref="areaSelectRef"
                                size="large"
                                v-model="searchForm.regionCode"
                                placeholder="请选择省市区"
                                @change="operateChange"
                            />
                        </el-form-item>
                        <el-form-item label="详细地址">
                            <el-input
                                v-model="searchForm.address"
                                placeholder="请输入详细地址"
                            />
                        </el-form-item>
                        <div class="search-btns detail-search-btns">
                            <el-button
                                type="primary"
                                size="mini"
                                icon="el-icon-search"
                                @click="doUpdateSearch"
                                >搜索</el-button
                            >
                            <el-button
                                type="default"
                                size="mini"
                                icon="el-icon-refresh"
                                @click="resetDialogClear"
                                >重置</el-button
                            >
                        </div>
                    </el-col>
                </el-row>
            </el-form>

            <el-card class="updateForm">
                <el-form
                    ref="updateForm"
                    :model="updateForm"
                    label-width="90px"
                >
                    <el-row class="filters">
                        <div class="flexDiv">
                            <div class="update-text" style="font-weight: bold">
                                文件
                            </div>
                            <el-row class="filters">
                                <el-form-item label="升级部件">
                                    <el-select
                                        style="width: 145px !important"
                                        v-model="updateForm.partType"
                                        :disabled="!searchForm.equipTypeCode"
                                        placeholder="请选择升级部件"
                                        @change="updatePartTypeChange"
                                    >
                                        <el-option
                                            v-for="item in componentList"
                                            :key="item.code"
                                            :label="item.name"
                                            :value="item.code"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="版本">
                                    <el-select
                                        style="
                                            width: 120px !important;
                                            margin-right: 10px;
                                        "
                                        v-model="updateForm.softwareVersionId"
                                        :disabled="
                                            !searchForm.equipTypeCode ||
                                            !updateForm.partType ||
                                            updateForm.useAutoGradeVersion
                                        "
                                        placeholder="请选择版本"
                                    >
                                        <el-option
                                            v-for="item in versionList"
                                            :key="item.id"
                                            :label="item.version"
                                            :value="item.id"
                                        >
                                        </el-option>
                                    </el-select>
                                    <el-tooltip
                                        :content="
                                            versionList.length == 0 ||
                                            autoUpdateList.length == 0
                                                ? '暂无自动升级版本，请先选择设备类型及部件'
                                                : '采用自动升级版本'
                                        "
                                        placement="top"
                                    >
                                        <el-switch
                                            :disabled="
                                                !searchForm.equipTypeCode ||
                                                !updateForm.partType ||
                                                versionList.length == 0 ||
                                                autoUpdateList.length == 0
                                            "
                                            v-model="
                                                updateForm.useAutoGradeVersion
                                            "
                                            @change="switchChange"
                                        >
                                        </el-switch>
                                    </el-tooltip>
                                </el-form-item>
                            </el-row>
                        </div>
                        <div class="flexDiv">
                            <div class="update-text" style="font-weight: bold">
                                规则
                            </div>
                            <el-row class="filters">
                                <el-form-item label="升级个数">
                                    <el-input-number
                                        class="ipt"
                                        :min="1"
                                        :max="50"
                                        :step="1"
                                        step-strictly
                                        size="mini"
                                        controls-position="right"
                                        placeholder="请输入升级个数"
                                        v-model="updateForm.upgradeCount"
                                    ></el-input-number>
                                </el-form-item>
                                <el-form-item label="间隔(分钟)">
                                    <el-input-number
                                        :min="1"
                                        :max="60"
                                        :step="1"
                                        step-strictly
                                        size="mini"
                                        controls-position="right"
                                        placeholder="请输入间隔"
                                        v-model="updateForm.interval"
                                    >
                                    </el-input-number>

                                    <el-tooltip
                                        content="是否开启定时"
                                        placement="top"
                                    >
                                        <el-switch
                                            v-model="updateForm.upgradeType"
                                            :active-value="1"
                                            :inactive-value="0"
                                            style="margin-left: 10px"
                                        >
                                        </el-switch>
                                    </el-tooltip>
                                </el-form-item>
                                <el-form-item
                                    style="margin-left: 5px"
                                    label="定时时间"
                                    v-if="updateForm.upgradeType"
                                >
                                    <el-date-picker
                                        style="width: 194px"
                                        :append-to-body="false"
                                        :popper-append-to-body="false"
                                        value-format="yyyy-MM-dd HH:mm:ss"
                                        format="yyyy-MM-dd HH:mm:ss"
                                        v-model="updateForm.upgradeTime"
                                        type="datetime"
                                        placeholder="选择定时时间"
                                    >
                                    </el-date-picker>
                                </el-form-item>

                                <div class="search-btns">
                                    <el-button
                                        type="primary"
                                        size="mini"
                                        :loading="updateLoading"
                                        icon="el-icon-upload2"
                                        @click="isUpdate"
                                        >开始升级</el-button
                                    >
                                </div>
                            </el-row>
                        </div>
                    </el-row>
                </el-form>
            </el-card>
            <el-row :gutter="10">
                <el-col :span="18">
                    <el-link class="link-text" :underline="false" type="danger"
                        >注：设备编码为红色文字的代表当前设备不可用</el-link
                    >
                    <el-link class="link-text" type="success" :underline="false"
                        >（已选择({{
                            +equipTotal - unselectData.length
                        }})个）</el-link
                    >
                    <Table
                        :height="isFullscreen ? '66vh' : '50vh'"
                        :tableHeader="equipTableHeader"
                        :tableData="equipTableData"
                        :tableLoading="handleListLoading"
                        :unselectData="unselectData"
                        @handleUnselectData="handleUnselectData"
                    >
                        <template slot="codes" slot-scope="scope">
                            <div class="codes">
                                <span
                                    :class="{
                                        isAllow: !scope.row.isAllowOperate,
                                    }"
                                    >{{ scope.row.code }}</span
                                >
                                <img
                                    v-if="scope.row.isOnline == 1"
                                    src="@/assets/image/online.png"
                                    alt=""
                                />
                                <img
                                    v-else
                                    src="@/assets/image/offline.png"
                                    alt=""
                                />
                            </div>
                        </template>
                        <template slot="softVersion" slot-scope="scope">
                            <span
                                style="text-align: left"
                                v-html="
                                    $options.filters.filterVersion(scope.row)
                                "
                            ></span>
                        </template>
                        <template slot="tags" slot-scope="scope">
                            <div class="tags-content">
                                <Tags
                                    :currentRow="scope.row"
                                    @updateList="fetchData"
                                ></Tags>
                                <!-- <i
                                    class="el-icon-circle-plus-outline"
                                    @click="tagSetShow(scope.row)"
                                ></i> -->
                            </div>
                        </template>
                    </Table>

                    <pagination
                        v-if="equipTotal > 0"
                        :total="equipTotal"
                        :page.sync="searchForm.pageNum"
                        :limit.sync="searchForm.pageSize"
                        @pagination="getDetailList"
                    />
                </el-col>
                <el-col :span="6">
                    <el-link class="link-text" :underline="false" type="danger"
                        >取消升级（未选中）设备列表</el-link
                    >
                    <Table
                        style="width: 100%"
                        :tableHeader="unselectTableHeader"
                        :tableData="unselectData"
                        :height="isFullscreen ? '66vh' : '50vh'"
                    >
                        <template slot="action" slot-scope="scope">
                            <i
                                class="el-icon-circle-close"
                                @click="cancelButton(scope.row)"
                            ></i>
                        </template>
                    </Table>
                </el-col>
            </el-row>
        </Dialog>

        <!-- 详情 -->
        <Dialog
            :visible="detailVisible"
            class="detail-dialog"
            width="80%"
            :isFullscreen="isDetailFullscreen"
            :isFooter="false"
            title="详情"
            @cancelDialog="cancelDetailDialog"
        >
            <i
                class="el-icon-full-screen"
                style="margin-top: -26px"
                @click="onFullscreen('isDetailFullscreen')"
            ></i>
            <div class="export-btns">
                <el-button
                    type="primary"
                    icon="el-icon-folder-checked"
                    @click="isExport"
                    size="small"
                    :loading="exportBtnLoading"
                    >导出版本不符设备号</el-button
                >
            </div>
            <div
                class="table-box"
                :style="{ 'max-height': isDetailFullscreen ? '78vh' : '60vh' }"
            >
                <Table
                    :tableHeader="detailTableHeader"
                    :tableData="detailTableData"
                    :tableLoading="detailListLoading"
                >
                    <template slot="softVersion" slot-scope="scope">
                        <span
                            style="text-align: left"
                            v-html="$options.filters.filterVersion(scope.row)"
                        ></span>
                    </template>
                    <template slot="compareVersion" slot-scope="scope">
                        <el-popover
                            popper-class="popperClass"
                            placement="top-start"
                            width="200"
                            trigger="hover"
                            :content="`升级的版本与最新版本比较：${compareVersion(
                                scope.row
                            )}`"
                        >
                            <el-tag
                                slot="reference"
                                :type="
                                    compareVersion(scope.row).length == 2
                                        ? 'success'
                                        : 'danger'
                                "
                                >{{ compareVersion(scope.row) }}</el-tag
                            >
                        </el-popover>
                    </template>
                </Table>
            </div>
            <pagination
                v-if="detailTotal > 0"
                :total="detailTotal"
                :page.sync="detailForm.pageNum"
                :limit.sync="detailForm.pageSize"
                @pagination="getDetailData"
            />
        </Dialog>

        <!-- 编辑 弹框 -->
        <Dialog
            :visible="editVisible"
            width="35%"
            title="编辑"
            @confirmDialog="confirmEditDialog"
            @cancelDialog="cancelEditDialog"
        >
            <el-form
                class="dialog-form"
                ref="dialogEditForm"
                :model="dialogEditForm"
                label-width="140px"
                :rules="dialogEditRules"
            >
                <el-form-item label="升级版本号">
                    <el-input
                        class="ipt"
                        disabled
                        v-model="currentRow.softwareVersion"
                        placeholder="升级版本号"
                    ></el-input>
                </el-form-item>
                <el-form-item label="设备类型">
                    <el-input
                        class="ipt"
                        disabled
                        v-model="currentRow.equipTypeName"
                        placeholder="选择升级文件自动回显"
                    ></el-input>
                </el-form-item>
                <el-form-item label="设备部件">
                    <el-input
                        class="ipt"
                        disabled
                        v-model="currentRow.partTypeName"
                        placeholder="选择升级文件自动回显"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="升级时间" prop="upgradeTime">
                    <el-date-picker
                        class="ipt"
                        :append-to-body="false"
                        :popper-append-to-body="false"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        format="yyyy-MM-dd HH:mm:ss"
                        v-model="dialogEditForm.upgradeTime"
                        type="datetime"
                        placeholder="选择升级时间"
                    >
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="升级个数" prop="upgradeRule.count">
                    <el-input-number
                        class="ipt"
                        :min="1"
                        :max="50"
                        :step="1"
                        step-strictly
                        size="medium"
                        controls-position="right"
                        placeholder="请输入升级个数"
                        v-model="dialogEditForm.upgradeRule.count"
                    ></el-input-number>
                </el-form-item>
                <el-form-item label="间隔（分钟）" prop="upgradeRule.interval">
                    <el-input-number
                        class="ipt"
                        :min="1"
                        :max="60"
                        :step="1"
                        step-strictly
                        size="medium"
                        controls-position="right"
                        placeholder="请输入间隔"
                        v-model="dialogEditForm.upgradeRule.interval"
                    >
                    </el-input-number>
                    <!-- <span class="suffix">分钟</span> -->
                </el-form-item>
                <el-form-item label="任务说明">
                    <el-input
                        class="ipt"
                        type="textarea"
                        placeholder="请输入任务说明"
                        rows="5"
                        colum="3"
                        v-model="dialogEditForm.remark"
                    ></el-input>
                </el-form-item>
            </el-form>
        </Dialog>
    </div>
</template>

<script>
import { partType, exportEquip, softwareVersions } from "@/api/file";
import { equipment, operator, batchUpdate } from "@/api/factuer";

import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "../components/table";
import Dialog from "@/components/Dialog";

import { handleConfirm } from "@/utils/messageBox";
import { removeNullUndefined } from "@/utils/index.js";
import { businessStatus, isOnlineStatus, executeData } from "@/utils/config";

import { mapState } from "vuex";
import Tags from "@/views/equipment/equipentry/components/tags.vue";

export default {
    components: { Pagination, Table, Dialog ,Tags},
    filters: {
        filterVersion(item) {
            // 转换后的二维数组
            if (
                item.equipSoftwareVersions &&
                item.equipSoftwareVersions.length > 0
            ) {
                let arrayTwo = Object.values(
                    item.equipSoftwareVersions.reduce((res, item) => {
                        res[item.partType]
                            ? res[item.partType].push(item)
                            : (res[item.partType] = [item]);
                        return res;
                    }, {})
                );
                let jsons = "";
                arrayTwo.map((item, index) => {
                    jsons += "<div>" + item[0].partTypeName + "：";
                    item.filter((qq, inx) => {
                        jsons +=
                            item.length > 1
                                ? `<span class="addrId">${qq.addrId}</span> ${qq.version}；`
                                : qq.version;
                    });
                    jsons += "</div>";
                });
                return jsons;
            } else {
                return "";
            }
        },
    },
    //放置与data同级
    options: {
        styleIsolation: "shared",
    },

    data() {
        return {
            list: null,
            listLoading: false,
            handleListLoading: false,
            detailListLoading: false,
            total: 0,
            updateSearchForm: {
                pageNum: 1,
                pageSize: 15,
                endUpgradeTime: "",
                startUpgradeTime: "",
                type: "",
            },
            rangeData: [],
            searchForm: {
                pageNum: 1,
                pageSize: 15,
                organizationId: "",
                equipTypeCode: "",
                operatorId: "",
                partType: "",
                statuses: [],
                version: "",
                isOnline: "",
                codes: "",
                regionCode: "",
                address: "",
                tagIds: [],
            },
            detailForm: {
                pageNum: 1,
                pageSize: 15,
            },
            detailTableData: [],
            detailTotal: 0,
            updateForm: {
                partType: "",
                softwareVersionId: "",
                upgradeCount: 1,
                interval: 1,
                useAutoGradeVersion: false,

                ignoreIds: [],
                upgradeTime: "",
                upgradeType: 0,
            },

            updateSearchData: {},

            updateTableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "60",
                    fixed: true,
                },
                {
                    label: "设备类型",
                    prop: "equipTypeName",
                },
                {
                    label: "部件",
                    prop: "partTypeName",
                },
                {
                    label: "升级时间",
                    prop: "upgradeTime",
                },
                {
                    label: "执行情况",
                    slot: "executes",
                },
                {
                    label: "类型",
                    prop: "type",
                    formatter: (item) => {
                        let classify =
                            this.enumsJson.EQUIP_UPGRADE_TASK_TYPE.find((p) => {
                                return p.code == item.type;
                            });
                        return classify != undefined
                            ? classify.label
                            : item.type;
                    },
                },
                {
                    label: "版本",
                    prop: "softwareVersion",
                },
                {
                    label: "操作人",
                    prop: "createBy",
                },
                { slot: "action", label: "操作" },
            ],
            tableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "60",
                    fixed: true,
                },
                {
                    label: "设备编码",
                    prop: "pageviews",
                },
                {
                    label: "运营商",
                    prop: "author",
                },
                {
                    label: "版本",
                    prop: "pageviews",
                },
                {
                    label: "更新时间",
                    prop: "display_time",
                },
                {
                    label: "升级指令下发结果",
                    prop: "display_time",
                },
            ],
            detailTableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "50",
                    fixed: true,
                },
                {
                    label: "设备编码",
                    prop: "equipCode",
                    width: "195",
                },
                {
                    label: "下发状态",
                    prop: "sendStatus",
                    formatter: (item) => {
                        let current =
                            this.enumsJson.EQUIP_UPGRADE_LOG_SEND_STATUS.find(
                                (pp) => pp.code == item.sendStatus
                            );
                        return current ? current.label : "";
                    },
                    width: "78",
                },
                {
                    label: "失败原因",
                    prop: "sendFailName",
                    width: "78",
                },
                {
                    label: "响应状态",
                    prop: "result",
                    formatter: (item) => {
                        return item.result || item.result == 0
                            ? this.enumsJson.LOG_STATUS.find(
                                  (pp) => pp.code == item.result
                              ).label
                            : "";
                    },
                    width: "78",
                },
                { slot: "softVersion", label: "最新版本" },
                {
                    label: "比较",
                    slot: "compareVersion",
                    width: "80",
                },
                {
                    label: "上报时间",
                    prop: "reportTime",
                    width: "155",
                },
            ],
            tableData: [],
            equipTableData: [],
            equipTableHeader: [
                {
                    type: "selection",
                    width: "40",
                    label: "多选",
                    fixed: "left",
                },
                {
                    label: "ID",
                    prop: "id",
                    width: "120",
                    tooltip: true,
                },
                { slot: "codes", label: "设备编码", width: "220" },
                {
                    label: "运营商",
                    prop: "operatorName",
                    width: "130",
                    tooltip: true,
                },
                {
                    label: "设备类型",
                    prop: "equipTypeName",
                    width: "78",
                },
                { slot: "tags", label: "标签" ,width:"130"},
                { slot: "softVersion", label: "版本" },
            ],
            equipTotal: 0,
            visible: false, //弹框标识

            unselectTableHeader: [
                { slot: "action", label: "操作", width: "50" },
                {
                    label: "ID",
                    prop: "id",
                    tooltip: true,
                },
                { label: "设备编码", prop: "code", width: "192" },
            ],
            areaSelectData: [], // options绑定的数据就是引入的 provinceAndCityData
            areaSelectDataProps: {
                children: "childrens",
                value: "code",
                label: "name",
                emitPath: false,
            },

            detailVisible: false, //详情dialog标识
            pickerOptions: {
                shortcuts: [
                    {
                        text: "最近一周",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 7
                            );
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "最近一个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 30
                            );
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "最近三个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 90
                            );
                            picker.$emit("pick", [start, end]);
                        },
                    },
                ],
            },

            operatorOption: [], //运营商option
            factuerOption: [], //厂商option
            equipTypeOption: [], //设备类型option
            businessStatus: businessStatus,
            isOnlineStatus: isOnlineStatus,
            componentList: [],
            currentRow: {},
            exportBtnLoading: false,
            versionList: [],
            autoUpdateList: [], //自动升级版本list
            updateLoading: false,
            platformType: this.$store.state.user.platformType,
            organizationId: this.$store.state.user.organizationId,
            isFullscreen: true, //是否全屏

            editVisible: false, //弹框标识
            dialogEditForm: {
                softwareVersionId: "",
                remark: "",
                partType: "",
                equipTypeCode: "",
                upgradeTime: "",
                upgradeRule: {
                    count: 1,
                    interval: 1,
                },
            },
            dialogEditRules: {
                upgradeTime: [
                    {
                        required: true,
                        message: "请选择升级时间",
                        trigger: "change",
                    },
                ],
                "upgradeRule.count": [
                    {
                        required: true,
                        message: "请输入升级个数",
                        trigger: "blur",
                    },
                ],
                "upgradeRule.interval": [
                    {
                        required: true,
                        message: "请输入升级间隔",
                        trigger: "blur",
                    },
                ],
            },

            updateOption: [],
            unselectData: [],

            isDetailFullscreen: true,
            tagsOption: [],
        };
    },
    computed: {
        ...mapState({
            enumsJson: (state) => state.enums.enums,
        }),
    },
    created() {
        if (this.platformType != "P") {
            //非平台用户
            this.searchForm.organizationId = this.organizationId;
        }
        this.fetchData();
        this.getOperator();
        this.getUpgradeList();
    },
    methods: {
        fetchData(val) {
            this.updateSearchForm.pageNum = val
                ? val.page
                : this.updateSearchForm.pageNum;
            this.listLoading = true;
            this.tableData = [];
            this.total = 0;
            if (this.rangeData.length > 0) {
                this.updateSearchForm.startUpgradeTime = this.rangeData[0];
                this.updateSearchForm.endUpgradeTime = this.rangeData[1];
            }
            equipment(
                "/upgrade/task/list",
                "post",
                {
                    ...removeNullUndefined(this.updateSearchForm),
                },
                1
            )
                .then((res) => {
                    this.tableData = res.data;
                    this.total = +res.total;

                    this.updateSearchForm.pageNum = +res.pageNum;
                })
                .finally(() => {
                    this.listLoading = false;
                });
        },
        getDetailList() {
            if (!this.searchForm.equipTypeCode) {
                this.$message.error("请选择设备类型");
                return;
            }
            this.handleListLoading = true;
            let param = { ...this.searchForm };

            if (param.codes) {
                param.codes = param.codes.split("\n").filter((item) => item);
            }
            if (param.codes.length == 1) {
                param.code = param.codes[0];
                delete param.codes;
            }
            equipment(
                "/version/list",
                "post",
                {
                    ...removeNullUndefined(param),
                },
                1
            )
                .then((res) => {
                    this.equipTableData = res.data;
                    this.equipTotal = +res.total;
                })
                .finally(() => {
                    this.handleListLoading = false;
                });
        },
        async organizeChange(e) {
            this.operatorOption = [];
            this.searchForm.operatorId = "";
            if (e) {
                let datas = await operator("/all", "get", {
                    organizationId: e,
                });
                this.operatorOption = datas.data;
            }
        },
        doUpdateSearch() {
            this.unselectData = [];
            this.equipTableData = [];
            this.equipTotal = 0;
            this.updateSearchData = { ...this.searchForm };
            this.getDetailList();
        },
        async getOperator() {
            this.areaSelectData = await this.$store.dispatch(
                "operator/generatorRegion"
            );
            this.equipTypeOption = await this.$store.dispatch(
                "operator/generatorEquipType"
            );
            this.tagsOption = await this.$store.dispatch(
                "operator/generatorTags"
            );
            if (this.equipTypeOption.length > 0) {
                this.searchForm.equipTypeCode = this.equipTypeOption[0].code;
                this.equipTypeChange(this.searchForm.equipTypeCode);
            }
        },
        async equipTypeChange(e) {
            this.componentList = [];
            this.searchForm.partType = "";

            this.updateForm.useAutoGradeVersion = false;
            this.updateForm.partType = "";
            this.updateForm.softwareVersionId = "";
            this.versionList = [];
            this.autoUpdateList = [];

            let data = await partType("/list", "get", { equipTypeCode: e });
            this.componentList = data.data;
        },

        async updatePartTypeChange() {
            this.updateForm.useAutoGradeVersion = false;
            this.updateForm.softwareVersionId = "";
            this.versionList = [];
            this.autoUpdateList = [];
            let datas = await softwareVersions("/all", "get", {
                equipTypeCode: this.updateSearchData.equipTypeCode,
                partType: this.updateForm.partType,
            });
            this.versionList = datas.data;
            this.autoUpdateList = datas.data.filter(
                (item) => item.isAutoUpgrade == 1
            );
        },
        switchChange(e) {
            if (e)
                this.updateForm.softwareVersionId = this.autoUpdateList[0].id;
        },
        operateChange(e) {},

        //限制输入特殊字符
        keyUp(e) {
            let str = e.target.value.replace(
                /[`~!@#$%^&*()_\-+=<>?:"{}|.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
                ""
            );
            e.target.value = str;
            this.searchForm.codes = str;
        },
        // 只能输入汉字、英文、数字
        keyInput(e) {
            let str = e.target.value.replace(/[^\a-\z\A-\Z0-9\n/]/g, "");
            e.target.value = str;
            this.searchForm.codes = str;
        },
        isUpdate() {
            if (this.equipTableData.length == 0) {
                this.$message.error("暂无可升级设备，请重新筛选！");
                return;
            } else if (this.unselectData.length == +this.equipTotal) {
                this.$message.error("请勾选要升级的设备!");
                return;
            } else if (!this.updateSearchData.equipTypeCode) {
                this.$message.error("请选择要升级的设备类型");
                return;
            } else if (!this.updateForm.partType) {
                this.$message.error("请选择要升级的部件");
                return;
            } else if (!this.updateForm.softwareVersionId) {
                this.$message.error("请选择升级版本");
                return;
            } else if (
                this.updateForm.upgradeType &&
                !this.updateForm.upgradeTime
            ) {
                this.$message.error("请选择升级定时时间");
                return;
            }
            handleConfirm("确定要升级吗？", "warning", "提示")
                .then((res) => {
                    this.doHandleUpdate();
                })
                .catch((err) => {});
        },
        doHandleUpdate() {
            let { ignoreIds, upgradeTime, upgradeType } = this.updateForm;
            let param = {
                softwareVersionId: this.updateForm.softwareVersionId,
                upgradeRule: {
                    count: this.updateForm.upgradeCount,
                    interval: this.updateForm.interval,
                },
                queryParam: { ...removeNullUndefined(this.updateSearchData) },
                ignoreIds: this.unselectData.map((item) => {
                    return item.id;
                }),
                upgradeTime,
                upgradeType,
            };
            
            if (param.queryParam.codes) {
                param.queryParam.codes = param.queryParam.codes.split("\n").filter((item) => item);
            }
            if (param.queryParam.codes && param.queryParam.codes.length == 1) {
                param.queryParam.code = param.queryParam.codes[0];
                delete param.queryParam.codes;
            }

            delete param.queryParam.pageNum;
            delete param.queryParam.pageSize;

            this.updateLoading = true;
            
            batchUpdate("/upgrade/batch/schedule", "post", param)
                .then((res) => {
                    if (res.code == 200) {
                        this.$message.success(res.message);
                        this.visible = false;
                        this.fetchData();
                    }
                })
                .finally(() => {
                    this.updateLoading = false;
                });
        },
        chekboxChange(e) {
            // if (e) this.updateForm.softwareVersionId = "";
        },
        async addDialog() {
            this.visible = true;

            if (this.platformType != "P" && this.operatorOption.length == 0) {
                this.organizeChange(this.organizationId);
            }
            if (this.platformType == "P" && this.factuerOption.length == 0) {
                this.factuerOption = await this.$store.dispatch(
                    "operator/generatorFactuer"
                );
            }
            this.searchForm.equipTypeCode = this.equipTypeOption[0].code;
            this.equipTypeChange(this.searchForm.equipTypeCode);
            this.doUpdateSearch();
        },
        // 弹框取消
        cancelDialog() {
            this.visible = false;
            this.isFullscreen = true;
            this.resetDialogSearch();
            this.equipTableData = [];
            this.equipTotal = 0;
        },
        detailDialog(row) {
            this.detailVisible = true;
            this.currentRow = { ...row };
            this.getDetailData();
        },
        getDetailData() {
            this.detailListLoading = true;
            equipment("/upgrade/log", "get", {
                ...this.detailForm,
                taskId: this.currentRow.id,
            })
                .then((res) => {
                    this.detailTableData = res.data ? res.data : [];
                    this.detailTotal = res.total ? +res.total : 0;
                })
                .finally(() => {
                    this.detailListLoading = false;
                });
        },
        cancelDetailDialog() {
            this.detailTableData = [];
            this.detailTotal = 0;
            this.exportBtnLoading = false;
            this.detailForm = {
                pageNum: 1,
                pageSize: 15,
            };
            this.detailVisible = false;
            this.isDetailFullscreen = true;
        },
        isExport() {
            handleConfirm("确定要导出版本不符设备号吗？", "warning", "提示")
                .then((res) => {
                    this.doExportExcel();
                })
                .catch((err) => {});
        },
        doExportExcel() {
            this.exportBtnLoading = true;
            exportEquip({
                taskId: this.currentRow.id,
            })
                .then((res) => {
                    if (res.code == 200) {
                        this.$message.success(res.message);
                        this.detailVisible = false;
                    }
                })
                .catch((err) => {
                    const content = err.data; // 这里试试res 不行就用res.data
                    const blob = new Blob([content]); //构造一个blob对象来处理数据
                    const fileName = "版本不符设备号.xlsx"; // 下载的文件名称 可以自定义

                    //对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
                    //IE10以上支持blob但是依然不支持download
                    if ("download" in document.createElement("a")) {
                        //支持a标签download的浏览器
                        const link = document.createElement("a"); //创建a标签
                        link.download = fileName; //a标签添加属性
                        link.style.display = "none";
                        link.href = URL.createObjectURL(blob);
                        document.body.appendChild(link);
                        link.click(); //执行下载
                        URL.revokeObjectURL(link.href); //释放url
                        document.body.removeChild(link); //释放标签
                    } else {
                        //其他浏览器
                        navigator.msSaveBlob(blob, fileName);
                    }
                })
                .finally(() => {
                    this.exportBtnLoading = false;
                });
        },
        resetSearch() {
            this.rangeData = [];
            this.updateSearchForm = {
                pageNum: this.updateSearchForm.pageNum,
                pageSize: this.updateSearchForm.pageSize,
                endUpgradeTime: "",
                startUpgradeTime: "",
                type: "",
            };
        },
        doSearch() {
            this.updateSearchForm.pageNum = 1;
            this.fetchData();
        },
        resetDialogSearch() {
            this.searchForm = {
                pageNum: 1,
                pageSize: 15,
                organizationId:
                    this.platformType != "P" ? this.organizationId : "",
                equipTypeCode:
                    this.equipTypeOption.length > 0
                        ? this.equipTypeOption[0].code
                        : "",
                operatorId: "",
                partType: "",
                statuses: [],
                version: "",
                isOnline: "",
                codes: "",
                regionCode: "",
                address: "",
                tagIds: [],
            };
            if (this.searchForm.equipTypeCode) {
                this.equipTypeChange(this.searchForm.equipTypeCode);
            }
            this.updateForm = {
                partType: "",
                softwareVersionId: "",
                upgradeCount: 1,
                interval: 1,
                useAutoGradeVersion: false,

                ignoreIds: [],
                upgradeTime: "",
                upgradeType: 0,
            };
            this.updateSearchData = {};
            this.unselectData = [];
            this.updateLoading  = false;
        },
        resetDialogClear() {
            this.resetDialogSearch();
        },
        onFullscreen(val) {
            this[val] = !this[val];
        },
        isDelete(row) {
            handleConfirm(
                "删除后不可恢复，确定执行此操作吗？",
                "warning",
                "提示"
            )
                .then((res) => {
                    this.doDelete(row);
                })
                .catch((err) => {
                    // do something cancel
                });
        },
        doDelete(row) {
            equipment(`/upgrade/task/delete/${row.id}`, "post").then((res) => {
                if (res.code == 200) {
                    this.$message.success(res.message);
                    this.fetchData();
                }
            });
        },

        // 编辑
        async editDialog(row) {
            this.editVisible = true;

            if (row.id) {
                this.currentRow = { ...row };
                let {
                    id,
                    softwareVersionId,
                    remark,
                    partType,
                    equipTypeCode,
                    upgradeTime,
                    upgradeRule,
                } = row;
                let uprule = JSON.parse(upgradeRule);
                this.dialogEditForm = {
                    id,
                    softwareVersionId,
                    remark,
                    partType,
                    equipTypeCode,
                    upgradeTime,
                    upgradeRule: {
                        count: uprule.count ? uprule.count : undefined,
                        interval: uprule.interval ? uprule.interval : undefined,
                    },
                };
            } else {
                this.currentRow = {};
            }
        },
        // 弹框取消
        cancelEditDialog() {
            this.editVisible = false;
            this.dialogEditForm = {
                softwareVersionId: "",
                remark: "",
                partType: "",
                equipTypeCode: "",
                upgradeTime: "",
                upgradeRule: {
                    count: 1,
                    interval: 1,
                },
            };
            this.currentRow = {};
        },
        // 弹框确认
        confirmEditDialog() {
            this.submitDialogForm("dialogEditForm");
        },
        submitDialogForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    handleConfirm(`确定要编辑吗？`, "warning", "提示")
                        .then((res) => {
                            this.isAddUpdate();
                        })
                        .catch((err) => {});
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        isAddUpdate() {
            let param = { ...this.dialogEditForm };
            let url = `/upgrade/task/update/${this.currentRow.id}`;
            equipment(url, "post", param, 1).then((res) => {
                if (res.code == 200) {
                    this.editVisible = false;
                    this.$message.success(res.message);
                    this.fetchData();
                }
            });
        },
        getUpgradeList() {
            softwareVersions("/autoupgrade/all", "get").then((res) => {
                this.updateOption = res.data;
            });
        },
        handleUnselectData(e) {
            this.unselectData = e;
        },
        cancelButton(row) {
            this.unselectData = this.unselectData.filter(
                (item) => item.id != row.id
            );
        },
        compareVersion(item) {
            let every = item.equipSoftwareVersions.every((item) => {
                return item.version == this.currentRow.softwareVersion;
            });
            if (every) {
                return "一致";
            }
            return "不一致";
        },
        executeFormatter(item) {
            let classify = executeData.find((p) => {
                return p.code == item;
            });
            return classify != undefined ? classify.label : item.status;
        },
    },
};
</script>
<style lang="scss">
.el-checkbox__inner {
    border-color: #5473e8;
}

.el-input-number__decrease,
.el-input-number__increase {
    display: inline-block;
    height: 94%;
}

.el-input-number--mini {
    line-height: 30px;
}
</style>

<style scoped lang="scss">
@import "@/styles/common.scss";

.area-select {
    .el-cascader {
        width: 100%;
    }
}

.filters {
    .el-form-item {
        width: 17%;
    }

    .el-form-item__content {
        width: auto;
    }
    .flexDiv {
        @include flexLayout(flex-start, flex-start);
        flex-direction: column;
    }
    .flexDiv:first-child {
        margin-right: 20px;
    }
}

.updateForm {
    padding: 5px 10px;
    margin-bottom: 10px;
    .el-form {
        width: 100%;
    }
    .el-form-item {
        width: auto !important;
    }
    ::v-deep .el-card__body {
        @include flexLayout(center, flex-start);
    }
    ::v-deep .el-input--prefix .el-input__inner {
        padding-right: 0 !important;
    }

    .filters {
        margin-bottom: 2px;
        .el-form-item {
            width: 20%;
        }
    }
}

::v-deep .el-card__body {
    padding: 0;
}

.update-table {
    height: 300px;
    overflow-y: auto;
}

.export-btns {
    margin: 10px 0;
}

.export-table {
    height: 350px;
    overflow-y: auto;
}

.update-search-form {
    padding-left: 8px;
    .el-form-item {
        margin-bottom: 8px;
    }
}

.codes {
    @include flexLayout(center, center);

    img {
        width: 20px;
        margin-left: 10px;
    }

    .isAllow {
        color: red;
    }
}

.el-icon-full-screen {
    position: absolute;
    right: 45px;
    color: rgb(144, 147, 153);
    cursor: pointer;
    font-size: 22px;
    display: inline-block;
    margin-top: -36px;
    font-weight: bold;
}

::v-deep .addrId {
    display: inline-block;
    width: 16px;
    height: 16px;
    line-height: 15px;
    font-size: 12px;
    border-radius: 50%;
    text-align: center;
    border: 1px solid #606266;
    transform: scale(0.95);
}

.link-text {
    margin-bottom: 10px;
    font-weight: bold;
}
.detail-dialog {
    ::v-deep .el-table__empty-block {
        min-height: 160px;
    }
    ::v-deep .el-dialog__header {
        padding-bottom: 0;
    }
    ::v-deep .el-dialog__body {
        padding-top: 0;
    }
}
::v-deep .el-input.is-disabled .el-input__inner {
    color: #333333;
}
.ipt {
    width: 100%;
}
.el-icon-circle-close {
    font-size: 18px;
    color: #f56c6c;
}
.handleDialog {
    ::v-deep .el-dialog__body {
        padding: 0 20px 10px;
    }
    .searchForm {
        margin-bottom: 0;
    }
    ::v-deep .pagination-container {
        padding: 10px 0 0;
    }
}
::v-deep .el-select__tags{
    .el-tag:first-child{
        max-width: 66%;
    }
}
</style>
